//
//  GYDPublishView.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/15.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import AVFoundation

public enum PublishType : Int {
    case Text //文字
    case PhotoVideo //照片 视频
    case Headlines //头条文章
    case Comments //点评
    case FriendsCircle //好友圈
    case Music //音乐
    case Signin //签到
    case Live //直播
    case More //更多
    case RedWallet //红包
    case Goods //商品
    case SecondShot //秒拍
}




class GYDPublishView: UIView {

    private let baseTag = 800
    private var dissmisButton : UIButton?
    private var backButton : UIButton?
    private var currentIndex = 0
    private var scrollView : UIScrollView?
    
    var dissmisBlock : (() -> Void)?
    var publishTypeBlock : ((publishType : PublishType) -> Void)?
    
    
    private lazy var buttonArray: [UIButton] = {
        () -> [UIButton] in
        return  self.createEightButtons()
    }()
    private lazy var oldFrameArray : [CGRect] = {
        () -> [CGRect] in
        return []
    }()
    private lazy var newFrameArray : [CGRect] = {
        () -> [CGRect] in
        return []
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //模糊背景
        self.setUpEffectView()
        //添加点击手势
        self.addTapGesture()
        //消失按钮
        self.addBottomView()
        //scrollView
        self.createScrollView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 创建视图
    /**
     添加模糊
     */
    private func setUpEffectView() -> Void {
        self.backgroundColor = UIColor.clearColor()
        let effectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
        effectView.frame = self.bounds
        self.addSubview(effectView)
    }
    /**
     添加dissmis按钮
     */
    private func addBottomView() -> Void {
        let dissmisButton = UIButton(type: UIButtonType.Custom)
        self.dissmisButton = dissmisButton
        dissmisButton.frame = CGRect(x: 0, y: self.frame.size.height - 49, width: self.frame.size.width, height: 49)
        dissmisButton.backgroundColor = UIColor.whiteColor()
        dissmisButton.addTarget(self, action: #selector(GYDPublishView.dissmissButtonCLick), forControlEvents: UIControlEvents.TouchUpInside)
        dissmisButton.setImage(UIImage(named: "tabbar_compose_background_icon_close"), forState: UIControlState.Normal)
        self.addSubview(dissmisButton)
    }
    /**
     创建滚动视图
     */
    private func createScrollView() -> Void {
        let top : CGFloat = GYDWindowHeight * 0.3
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: top, width: self.frame.size.width, height: GYDWindowHeight - top - 49))
        scrollView.backgroundColor = UIColor.clearColor()
        scrollView.contentSize = CGSize(width: GYDWindowWidth*2, height: scrollView.frame.height)
        scrollView.bounces = false
        scrollView.scrollEnabled = false
        scrollView.pagingEnabled = true
        self.scrollView = scrollView
        self.addSubview(scrollView)
        
        for button in self.buttonArray {
            scrollView.addSubview(button)
        }
        
    }
    /**
     创建8个按钮
     */
    private func createEightButtons() -> [UIButton] {
        
        var tempButtonArray : [UIButton] = []
        
        let titleArray = ["文字","照片/视频","头条文章","点评","好友圈","音乐","签到","直播","更多","红包","商品","秒拍"]
        let imageArray = ["tabbar_compose_idea","tabbar_compose_photo","tabbar_compose_headlines","tabbar_compose_review","tabbar_compose_friend","tabbar_compose_music","tabbar_compose_lbs","tabbar_compose_video","tabbar_compose_more","tabbar_compose_envelope","tabbar_compose_productrelease","tabbar_compose_shooting"]
        
        let width : CGFloat = GYDWindowWidth / 3.0
        let height = width
        for i in 0 ..< titleArray.count {
            let button = UIButton(type: UIButtonType.Custom)
            let r = i%6
            let c = i/6
            
            let frame = CGRect(x: CGFloat(r)*width, y: CGFloat(c)*height + GYDWindowHeight * 0.1, width: width, height: height)
            let newFrame = CGRect(x: CGFloat(r)*width, y: GYDWindowHeight, width: width, height: height)
            button.frame = newFrame
            button.tag = baseTag + i
            button.addTarget(self, action: #selector(GYDPublishView.buttonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            
            
            let imageView = UIImageView(image: UIImage(named: imageArray[i]))
            imageView.frame = CGRect(x: 0, y: 0, width: width*0.55, height: width*0.55)
            imageView.center = CGPoint(x: button.frame.size.width/2.0, y: button.frame.size.height*0.4)
            button.addSubview(imageView)
            
            let titleLabel = UILabel(frame: CGRect(x: 0, y: imageView.frame.size.height + imageView.frame.origin.y + 5, width: width, height: 15))
            titleLabel.text = titleArray[i]
            titleLabel.textColor = RGB(100, g: 100, b: 100)
            titleLabel.font = UIFont.systemFontOfSize(12)
            titleLabel.textAlignment = NSTextAlignment.Center
            button.addSubview(titleLabel)
            
            
            self.oldFrameArray.append(frame)
            self.newFrameArray.append(newFrame)
            
            tempButtonArray.append(button)
        }
        return tempButtonArray
    }
    
    
    
    // MARK: - 事件点击
    /**
     8个按钮点击
     */
    @objc private func buttonClick(button: UIButton) -> Void {
        let index = button.tag - baseTag
        if index == 8 {
            playMusic("composer_open")
            self.changeDissmisButtonFrame(true)
            self.scrollView?.setContentOffset(CGPoint(x:GYDWindowWidth, y: 0 ), animated: true)
        }else {
           
            var type : PublishType
            switch index {
            case 0:
                type = PublishType.Text
            case 1:
                type = PublishType.PhotoVideo
            case 2:
                type = PublishType.Headlines
            case 3:
                type = PublishType.Comments
            case 4:
                type = PublishType.FriendsCircle
            case 5:
                type = PublishType.Music
            case 6:
                type = PublishType.Signin
            case 7:
                type = PublishType.Live
            case 9:
                type = PublishType.RedWallet
            case 10:
                type = PublishType.Goods
            case 11:
                type = PublishType.SecondShot
            default:
                type = PublishType.More
            }
            
            self.dismiss { [unowned self] () -> Void in
                if let tempPublishBlock = self.publishTypeBlock {
                    tempPublishBlock(publishType: type)
                }
            }
        }
    }
    /**
     点击消失
     */
    private func addTapGesture() -> Void {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(GYDPublishView.dissmissButtonCLick))
        self.addGestureRecognizer(tapGesture)
    }
    
    @objc private func dissmissButtonCLick() -> Void {
        self.dismiss({() -> Void in })
    }
    
    /**
     消失
     */
    func dismiss(callBack : ()->()) -> Void {
        self.hiddenButtons()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            callBack()
            self.removeFromSuperview()
            if let tempDissmisBlock = self.dissmisBlock {
                tempDissmisBlock()
            }
        }
    }
    /**
     返回按钮点击
     */
    @objc private func back() -> Void {
        self.changeDissmisButtonFrame(false)
        self.scrollView?.setContentOffset(CGPoint(x:0, y: 0 ), animated: true)
    }
    
    
    // MARK: - 动画
    /**
     动画显示8个按钮
     */
    func showButtons() -> Void {
        var delay = 0.04
        for i in 0 ..< self.buttonArray.count {
            if i < 3  {
                let button = self.buttonArray[i]
                UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                    button.frame = self.oldFrameArray[i]
                    delay += 0.04
                    }, completion: nil)
            }else if i > 5 && i < 9 {
                let button = self.buttonArray[i]
                UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                    button.frame = self.oldFrameArray[i]
                    delay += 0.04
                    }, completion: nil)
            }else {
                let button = self.buttonArray[i]
                button.frame = self.oldFrameArray[i]
                continue
            }
        }
        playMusic("composer_open")
    }
    /**
     动画隐藏8个按钮
     */
    private func hiddenButtons() -> Void {
        var delay = 0.03*6
        for i in 0 ..< self.buttonArray.count {
            if i < 3  {
                if self.currentIndex == 0 {
                    let button = self.buttonArray[i]
                    UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                        button.frame = self.newFrameArray[i]
                        delay -= 0.03
                        }, completion: nil)
                }
            }else if i > 5 && i < 9 {
                if self.currentIndex == 0 {
                    let button = self.buttonArray[i]
                    UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                        button.frame = self.newFrameArray[i]
                        delay -= 0.03
                        }, completion: nil)
                }
            }else if i > 2 && i < 6 {
                if self.currentIndex == 1 {
                    let button = self.buttonArray[i]
                    UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                        button.frame = self.newFrameArray[i]
                        delay -= 0.03
                        }, completion: nil)
                }
            }else if i > 8 {
                if self.currentIndex == 1 {
                    let button = self.buttonArray[i]
                    UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                        button.frame = self.newFrameArray[i]
                        delay -= 0.03
                        }, completion: nil)
                }
            }
        }
        playMusic("composer_close")
    }

    
    /**
     是否改变dissmisButton 的frame
     */
    private func changeDissmisButtonFrame(status:Bool) -> Void {
        if status {
            self.currentIndex = 1
            if let tempBackButton = self.backButton {
                tempBackButton.removeFromSuperview()
            }
            let backButton = UIButton(type: UIButtonType.Custom)
            self.backButton = backButton
            backButton.frame = CGRect(x: 0, y: self.frame.size.height - 49, width: self.frame.size.width/2.0, height: 49)
            backButton.backgroundColor = UIColor.whiteColor()
            backButton.addTarget(self, action: #selector(GYDPublishView.back), forControlEvents: UIControlEvents.TouchUpInside)
            backButton.setImage(UIImage(named: "tabbar_compose_background_icon_return"), forState: UIControlState.Normal)
            self.addSubview(backButton)
            
            self.dissmisButton?.frame = CGRect(x: self.frame.size.width/2.0, y: self.frame.size.height - 49, width: self.frame.size.width/2.0, height: 49)
            
        }else {
            self.currentIndex = 0
            if let tempBackButton = self.backButton {
                tempBackButton.removeFromSuperview()
                self.backButton = nil
                self.dissmisButton?.frame = CGRect(x: 0, y: self.frame.size.height - 49, width: self.frame.size.width, height: 49)
            }
        }
    }
    deinit {
        print("delloc -- GYDPublishView")
    }
    
}
